package com.ebookstore.dao;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

import com.ebookstore.common.HibernateSessionFactory;
import com.ebookstore.dto.BaseDTO;
import com.ebookstore.exception.EBookStoreException;

public class BaseDAO extends AbstractDAO {
	// hibernate会话对象
	private static Session session = HibernateSessionFactory
			.getCurrentSession();

	public BaseDAO() {
		super();
	}

	/**
	 * 添加对象
	 * 
	 * @param object
	 * @return
	 * @throws EBookStoreException
	 */
	public BaseDTO addObject(final BaseDTO object) throws EBookStoreException {
		if (object == null)
			throw new EBookStoreException("The Object is null");
		session.beginTransaction();
		session.save(object);
		session.getTransaction().commit();
//		session.close();
		return object;
	}

	/**
	 * 删除对象
	 * 
	 * @param object
	 *            要删除的对象
	 * @throws EBookStoreException
	 */
	public void deleteObject(final BaseDTO object) throws EBookStoreException {
		if (object == null)
			throw new EBookStoreException("The Object is null");
//		if(!session.isOpen())
			session.beginTransaction();
		session.delete(object);
		session.getTransaction().commit();
//		session.close();
		
	}

	/**
	 * 删除指定类型对象
	 * 
	 * @param id
	 *            删除类型的id
	 * @param clazz
	 *            删除的类型
	 * @throws EBookStoreException
	 */
	public void deleteObject(int id, Class clazz) throws EBookStoreException {
		Object object = session.load(clazz, new Integer(id));
		if (object == null)
			throw new EBookStoreException("The Object is null");
		session.beginTransaction();
		session.delete(object);
		session.getTransaction().commit();
//		session.close();
	}

	/**
	 * 更新对象
	 * 
	 * @param object
	 * @return
	 * @throws EBookStoreException
	 */
	public BaseDTO updateObject(BaseDTO object) throws EBookStoreException {
		if (object == null)
			throw new EBookStoreException("The Object is null");
		session.beginTransaction();
		session.update(object);
		System.out.println("BaseDAO.updateObject():update()");
		session.getTransaction().commit();
//		session.close();
		return object;
	}

	/**
	 * 保存或更新对象
	 * 
	 * @param object
	 * @return
	 * @throws EBookStoreException
	 */
	public BaseDTO saveOrUpdate(BaseDTO object) throws EBookStoreException {
		if (object == null)
			throw new EBookStoreException("The Object is null");
		session.beginTransaction();
		session.saveOrUpdate(object);
		session.getTransaction().commit();
		session.flush();
		return object;
	}

	/**
	 * 执行sql语句
	 * 
	 * @param sql
	 */
	public void executeSql(String sql) {
		executeSql(sql, null);
	}

	/**
	 * 按不同类型执行sql语句，如果为procedure，则执行存储过程
	 * 
	 * @param sql
	 * @param sqltype
	 */
	public void executeSql(String sql, String sqltype) {
		try {
			Connection con = session.connection();
			sqltype = (sqltype == null) ? "sqlstmt" : sqltype;
			if (sqltype.equals("procedure")) {
				CallableStatement cstmt = con.prepareCall(sql);
				cstmt.executeUpdate();
			} else {
				PreparedStatement stmt = con.prepareStatement(sql);
				stmt.executeUpdate();
			}
			session.flush();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 通过id和类型查找对象
	 * 
	 * @param id
	 * @param dtoclass
	 * @return
	 */
	public Object findById(String id, Class dtoclass) {
		Object obj = session.get(dtoclass, id);
		session.flush();
		return obj;
	}

	/**
	 * 通过id和类型查找对象
	 * 
	 * @param id
	 * @param dtoclass
	 * @return
	 */
	public Object findById(int id, Class dtoclass) {
		System.out.println("BaseDao.findById()");
		
		try {
			Object obj = session.get(dtoclass, new Integer(id));
			System.out.println("BaseDao.findById()：查找结果是否为空"+(obj==null));
			session.flush();
			return obj;
		} catch (Exception e) {
			System.out.println("basedao.findbyid():exception");
			e.printStackTrace();
			return null;
		}
		
		
	}

	/**
	 * 通过HQL查询
	 * 
	 * @param hql
	 * @return
	 */
	public List findByHql(String hql) {
		Query q = session.createQuery(hql);
		System.out.println("BaseDAO.findbyhql():query q==null  "+(q.list()==null));
		return q.list();
	}

	/**
	 * 通过HQL查询，并且可以指定开始的记录和最大的记录数
	 * 
	 * @param hql
	 * @param firstValue
	 * @param maxValue
	 * @return
	 */
	public List findByHql(String hql, int firstValue, int maxValue) {
		Query q = session.createQuery(hql);
		q.setMaxResults(maxValue);
		q.setFirstResult(firstValue);
		return q.list();
	}
}
